const db = new Dexie("web");
const chargeTabs = {};

db.version(1).stores({
    website: 'id,name,url,code', store: "id,val", visit: "++id,date,title,url",
});
db.open();

function saveVisit(date, title, url) {
    db.visit.put({date, title, url});
}

setInterval(() => {
    db.visit.offset(0)
        .limit(1000).toArray(data => {
        fetch("http://hex.wang:8008/hub/api/record/visit", {
            "headers": {
                "accept": "*/*",
                "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
                "content-type": "application/json;",
                "token": "76214654aeb72-4448-9f68-1e624d3d59fd"
            },
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": JSON.stringify(data),
            "method": "POST",
            "mode": "cors",
            "credentials": "omit"
        }).then((res) => {
            if (200 == res.status) {
                data.forEach(item => {
                    db.visit.delete(item.id);
                })
            }

        });
    });
}, 600000);


function saveWebsite(id, name, url, code) {
    db.website.put({id, name, url, code});
}

function deleteById(id) {
    db.website.delete(id);
}

function searchByName(res, name, pageSize, pageNum) {
    let web = null;
    if (name != null) {
        web = db.website.where("name")
            .startsWithAnyOfIgnoreCase(name)

    } else {
        web = db.website;
    }
    if (pageSize != null && pageNum != null) {
        let start = pageSize * (pageNum - 1);
        web = web
            .offset(start)
            .limit(pageNum);
    }
    web.toArray()
        .then(data => {
            res(data);
        });
}

function addChargeTab(tabId, webId) {
    chargeTabs[tabId] = webId;
}

chrome.tabs.onRemoved.addListener((id) => {
    delete chargeTabs[id];
});

chrome.tabs.onUpdated.addListener(function (id, info, tab) {
    //判断是否由tab页创建
    if (info.status == "complete") {
        let webId = chargeTabs[id];
        if (webId) {
            db.website.where("id")
                .equals(webId).toArray().then(data => {
                data.forEach(item => {
                    if (item.code) {
                        let c = item.code.trim();
                        if (c.startsWith("//LOAD")) {
                            let end = c.indexOf("\n");
                            let jsArray = c.substring(6, end).split(/\s+/);
                            jsArray.forEach(file => {
                                if (file != "") {
                                    chrome.tabs.executeScript(id, {file: file.trim()});
                                }
                            });
                        }
                        setTimeout(() => {
                            chrome.tabs.executeScript(id, {code: item.code});
                        }, 1000)

                    }

                })
            });
        }
    }
});

function store(id, val) {
    db.store.put({id, val});
}

function load(id, res) {
    return db.store.get(id).then((data) => {
        res(data);
    });
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    let m = request.m;
    let p = request.p;
    if (p == null) {
        p = [sendResponse];
    } else {
        p.push(sendResponse);
    }
    if (m && window[m]) {
        window[m].apply(null, p)
    }
    return true
});